import axios from "axios";
// import { Loading, Message } from 'element-ui';
// import store from "store";
import qs from "qs";
import vuex from "@/store";
import { Toast } from "vant";
axios.defaults.headers["Content-Type"] = "application/x-www-form-urlencoded";
const http = axios.create({
  baseURL: "https://huiduji.bigchun.com",
  // baseURL: "https://f-m.bigchun.com",
  timeout: 20000
});
http.baseURL = 'https://huiduji.bigchun.com'
let loading;
const delay = 600;
let timeout

http.interceptors.request.use(
  config => {
    const token = vuex.state.token;
    if (config.method == "post") {
      config.data = qs.stringify(config.data);
    }
    if (token && config.method == "post") {
      // console.log(config.data);
      config.data += `&token=${token}`;
      // config.data += `&token=d4d2758d-a2a8-4283-82d6-6ec55b6b84d0`;
    }
    if (token && config.method == "get") {
      if (config.params) {
        config.params.token = token;
      } else {
        config.params = {
          token
        };
      }
    }
    if (timeout) {
      clearTimeout(timeout);
      timeout = null;
    }

    timeout = setTimeout(() => {
      loading = Toast.loading({
        message: "请求中...",
        forbidClick: true
      });
    }, delay);

    return config;
  },
  err => Promise.reject(err)
);

http.interceptors.response.use(
  response => {
    console.log(response.data);
    if (timeout) {
      clearTimeout(timeout);
      timeout = null;
    }

    if (loading) {
      loading.clear();
    }
    if (!response.data.code) {
      Toast.fail(response.data.msg);
      return Promise.reject(response);
    }
    return response.data;
  },
  err => {
    console.log(err);
    if (timeout) {
      clearTimeout(timeout);
      timeout = null;
    }

    if (loading) {
      loading.clear();
    }

    if (err.response.status === 401) {
      store.remove("token");
      return Promise.reject(err);
    }

    if (err.response.status !== 200) {
      Toast.fail(err.response.data.msg);
      return err.response;
    }

    return Promise.reject(err);
  }
);

export default http;
